﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TSV.Areas.Administration.Models;
using TSV.Models.Entities;
using TSV.Models;
using TSV.Library.Common;
using TSV.Library.Attributes;

namespace TSV.Areas.Administration.Controllers
{
    public class CollaboratorController : BaseController
    {
        private CollaboratorDao dao = new CollaboratorDao();
        //
        // GET: /Administration/Collaborator/
        [CrmAuthorizeAttribute(Module = Modules.QL_Cong_Tac_Vien, Rights = Permissions.Doc)]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        public ActionResult GetListJQGrid(string name)
        {
            //grid constant => duy hung

            List<Collaborator> collaboratorList = dao.GetList();

            #region JQGrid Params
            string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
            string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
            int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
            int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);
            #endregion

            #region search
            string searchName = string.Empty;
            if (!string.IsNullOrEmpty(name.Trim()) && !name.Trim().Equals(Constants.COLLABORATOR_NAME))
            {
                collaboratorList = collaboratorList.Where(c => c.FullName.Trim().ToLower().Contains(name.Trim().ToLower())).ToList<Collaborator>();
            }
            #endregion



            int totalRecords = collaboratorList.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
            int currentPage = CommonFunc.SetJqGridPageIndex(totalRecords, pageIndex, rowCount);
            var finalList = dao.Sort(collaboratorList, sortColumn, sortOrder)
                                  .Skip((currentPage - 1) * rowCount)
                                   .Take(rowCount);

            var jsonData = new
            {
                total = totalPages,
                page = currentPage,
                records = totalRecords,
                rows = (
                    from m in finalList
                    select new
                    {
                        i = m.ID,
                        cell = new string[] {
                            m.ID.ToString(),
                            HttpUtility.HtmlEncode(m.FullName),
                            (m.Gender == true) ? "Nam" : "Nữ",                                                       
                            HttpUtility.HtmlEncode(m.Address),
                            HttpUtility.HtmlEncode(m.Phone),
                            HttpUtility.HtmlEncode(m.Email),
                            m.CreateDate.ToString(Constants.DATETIME_FORMAT),                                                        
                            "<input type=\"button\" class=\"icon edit\" title=\"Cập nhật\" onclick=\"JS_LIB.popup('/Administration/Collaborator/Edit/" + m.ID.ToString() + "', 'Cập nhật', 400)\" />"
                        }
                    }
                ).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        //
        // GET: /Administration/Collaborator/Create
        
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Administration/Collaborator/Create
        
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Administration/Collaborator/Edit/5
        [CrmAuthorizeAttribute(Module = Modules.QL_Cong_Tac_Vien, Rights = Permissions.Doc)]
        public ActionResult Edit(int id)
        {
            Collaborator collaborator = dao.GetById(id);
            return View(collaborator);
        }

        //
        // POST: /Administration/Collaborator/Edit/5
        [CrmAuthorizeAttribute(Module = Modules.QL_Cong_Tac_Vien, Rights = Permissions.Sua, ShowAtCurrentPage = true)]
        [HttpPost]
        public ActionResult Edit(Collaborator collaborator, FormCollection collection)
        {
            try
            {
                string gender = collection.GetValues("Gender")[0];
                if (gender.Equals("Nam"))
                {
                    collaborator.Gender = true;
                }
                else
                {
                    collaborator.Gender = false;
                }
                // TODO: Add update logic here
                Message msg = dao.Update(collaborator);
                ShowMessage(msg);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Cong_Tac_Vien, Rights = Permissions.Xoa, ShowAtCurrentPage = true)]
        public ActionResult DeleteList(string id)
        {            
            Message msg = dao.DeleteList(id);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }
    }
}
